﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Web;
using System.Web.Security;
using Castle.MonoRail.Framework;
using Rodunu.Movies.Interfaces.Security;
using Rodunu.Movies.Security;
using Rodunu.Movies.Web.Security;

namespace Rodunu.Movies.Web.Filters
{
    public class AuthenticationFilter : IFilter
    {
        #region Private Members

        private readonly IUserAuthentication securityService;
        private readonly WebAuthentication _webAuthentication;

        #endregion

        #region Controllers

        public AuthenticationFilter()
        {
            securityService = new UserAuthentication();
            _webAuthentication = new WebAuthentication();
        }

        #endregion

        #region IFilter Members

        public bool Perform(ExecuteEnum exec, IRailsEngineContext context, Controller controller)
        {
            string cookie = context.Request.ReadCookie("RodunuCookie");
            if (String.IsNullOrEmpty(cookie))
                return NotLoggedUser();
            return LogUserInFromCookie(context, cookie, controller);

            //string cookieContent = null;
            //try
            //{
            //    cookieContent = context.Request.ReadCookie(FormsAuthentication.FormsCookieName);
            //}
            //catch (Exception ex)
            //{
            //    //throw  new Exception(FormsAuthentication.FormsCookieName);
            //}

            //if (cookieContent == null)
            //    return NotLoggedUser();

            //FormsAuthenticationTicket ticket = null;
            //try
            //{
            //    ticket = FormsAuthentication.Decrypt(cookieContent);
            //}
            //catch (Exception ex)
            //{
            //   // throw new Exception("asdf");
            //}

            //if (ticket == null || ticket.Expired)
            //    return NotLoggedUser();

            //return LogUserIn(context, cookieContent, ticket, controller);
        }

        private bool LogUserInFromCookie(IRailsEngineContext context, string cookie, Controller controller)
        {
            long userId;
            try
            {
                userId = Convert.ToInt64(cookie);
            }
            catch (Exception ex)
            {
                return NotLoggedUser();
            }

            Contracts.UserInfo user = securityService.ReValidate(userId);
            user.IsLoggedIn = true;
            user.IsLoaded = true;
            context.CurrentUser = user;
            _webAuthentication.SetAuthCookie(user, true, string.Empty, context.Response);
            Thread.CurrentPrincipal = user;
            controller.PropertyBag["authCookieContent"] = cookie;
            return true;
        }

        private bool LogUserIn(IRailsEngineContext context, string cookieContent, FormsAuthenticationTicket ticket, Controller controller)
        {
            try
            {
                int userId = Convert.ToInt32(ticket.UserData);
                Contracts.UserInfo user = securityService.ReValidate(userId);
                user.Id = 1;
                user.IsLoggedIn = true;
                user.IsLoaded = true;
                context.CurrentUser = user;

                //_webAuthentication.SetAuthCookie(user, true, "Rodunu");
                Thread.CurrentPrincipal = user;

                controller.PropertyBag["authCookieContent"] = cookieContent;
            }
            catch (Exception ex)
            {
                //throw new Exception(ticket.UserData);
                return NotLoggedUser();
            }
            return true;
        }

        private static bool NotLoggedUser()
        {
            var nlUser = new Contracts.UserInfo();
            nlUser.IsLoggedIn = false;
            nlUser.UserName = "Guest";
            Thread.CurrentPrincipal = nlUser;
            return true;
        }

        #endregion

    }
}
